<template>
  <view class="profile-container">
    <scroll-view scroll-y class="content-scroll">
      <!-- 顶部背景 -->
      <view class="header-background"></view>

      <!-- 用户信息卡片 -->
      <view class="user-card">
        <image class="user-avatar" :src="safeImageUrl(userInfo?.avatarUrl, 'avatar')" mode="aspectFill"></image>
        <text class="user-name">{{ userInfo?.nickname || '未设置昵称' }}</text>
        <text class="user-role">{{ getRoleText(userInfo?.role) }}</text>
        <view class="user-details">
          <view class="detail-item">
            <text class="icon">📱</text>
            <text>{{ userInfo?.phone || '未设置手机' }}</text>
          </view>
          <view class="detail-item">
            <text class="icon">✉️</text>
            <text>{{ userInfo?.email || '未设置邮箱' }}</text>
          </view>
        </view>
        <button class="edit-btn" @click="navigateToEdit">
          <text>编辑资料</text>
        </button>
      </view>
      
      <!-- 家庭信息 -->
      <view class="info-section" v-if="familyInfo">
        <view class="section-header">
          <text class="section-title">我的家庭</text>
        </view>
        <view class="family-card">
          <text class="family-name">{{ familyInfo.name }}</text>
          <view class="family-meta">
            <text class="meta-item">{{ familyInfo.memberCount }} 位成员</text>
            <view class="invite-code">
              <text>邀请码: {{ familyInfo.inviteCode }}</text>
              <button class="copy-btn" @click="copyInviteCode">复制</button>
            </view>
          </view>
        </view>
      </view>

      <!-- 个人统计 -->
      <view class="info-section">
        <view class="section-header">
          <text class="section-title">个人统计</text>
        </view>
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-number">{{ userStats.momentCount || 0 }}</text>
            <text class="stat-label">发布动态</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ userStats.photoCount || 0 }}</text>
            <text class="stat-label">上传照片</text>
          </view>
          <view class="stat-item">
            <text class="stat-number">{{ userStats.likeCount || 0 }}</text>
            <text class="stat-label">获得点赞</text>
          </view>
        </view>
      </view>

      <!-- 退出登录 -->
      <view class="logout-section">
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { mapState, mapActions, mapGetters } from 'vuex';
import imageHelper from '@/utils/imageHelper'
import { api } from '@/utils/request'
import config from '@/utils/config'

export default {
  data() {
    return {
      showEditModal: false,
      editForm: {
        nickname: '',
        phone: '',
        email: ''
      },
      userStats: {
        momentCount: 0,
        photoCount: 0,
        likeCount: 0
      }
    };
  },
  computed: {
    ...mapState('user', ['userInfo']),
    ...mapState('family', ['familyInfo']),
  },
  onShow() {
    this.loadUserInfo();
    this.loadFamilyInfo();
    this.loadUserStats();
  },
  methods: {
    ...mapActions('user', ['loadUserInfo', 'updateUserInfo', 'logout']),
    
    getRoleText(role) {
      switch(role) {
        case 'admin': return '管理员';
        case 'member': return '普通成员';
        default: return '未知';
      }
    },
    
    openEditModal() {
      this.editForm = {
        nickname: this.userInfo?.nickname || '',
        phone: this.userInfo?.phone || '',
        email: this.userInfo?.email || ''
      };
      this.showEditModal = true;
    },
    
    closeEditModal() {
      this.showEditModal = false;
    },
    
    async saveProfile() {
      try {
        await this.updateUserInfo(this.editForm);
        uni.showToast({ title: '保存成功' });
        this.closeEditModal();
      } catch (error) {
        uni.showToast({ title: '保存失败', icon: 'none' });
      }
    },
    
    async loadUserStats() {
      try {
        const stats = await this.$store.dispatch('user/getUserStats');
        if (stats) {
          this.userStats = stats;
        }
      } catch (error) {
        console.error('加载用户统计数据失败', error);
        // 保留本地的默认值或上次加载的值
      }
    },
    
    async logout() {
      uni.showModal({
        title: '确认',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            await this.logout();
            uni.reLaunch({ url: '/pages/login/login' });
          }
        }
      });
    },

    // 加载家庭信息
    async loadFamilyInfo() {
      if (this.userInfo && this.userInfo.familyId) {
        try {
          const response = await api.get(`/user/my-family`)
          if (response.code === 200) {
            this.$store.commit('family/SET_FAMILY_INFO', response.data);
          }
        } catch (error) {
          console.error('加载家庭信息失败:', error)
        }
      }
    },

    // 安全获取图片URL
    safeImageUrl(url, type = 'avatar') {
      return imageHelper.safeImageUrl(url, type)
    },

    navigateToEdit() {
      uni.navigateTo({ url: '/pages/profile/edit' });
    },

    copyInviteCode() {
      uni.setClipboardData({
        data: this.familyInfo?.inviteCode || '',
        success: function () {
          uni.showToast({ title: '邀请码已复制', icon: 'none' });
        },
        fail: function () {
          uni.showToast({ title: '复制失败', icon: 'none' });
        }
      });
    },

    async handleLogout() {
      uni.showModal({
        title: '确认',
        content: '确定要退出登录吗？',
        success: async (res) => {
          if (res.confirm) {
            await this.logout();
            uni.reLaunch({ url: '/pages/login/login' });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #fafafa;
}

.content-scroll {
  height: 100vh;
}

.header-background {
  height: 160rpx;
  background-color: #34495e;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: -1;
}

.user-card {
  background-color: #fff;
  padding: 32rpx;
  text-align: center;
  border-bottom: 16rpx solid #fafafa;
  position: relative;
}

.user-avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 48rpx;
  margin-bottom: 16rpx;
  border: 2px solid #f5f5f5;
}

.user-name {
  display: block;
  font-size: 28rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
  color: #1a1a1a;
}

.user-role {
  display: block;
  font-size: 24rpx;
  color: #7f8c8d;
  margin-bottom: 24rpx;
}

.user-details {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 32rpx;
  margin-bottom: 24rpx;
  flex-wrap: wrap;
}

.detail-item {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #555555;
}

.icon {
  margin-right: 8rpx;
  font-size: 24rpx;
  color: #95a5a6;
}

.edit-btn {
  background-color: #34495e;
  color: white;
  border-radius: 8rpx;
  padding: 12rpx 32rpx;
  font-size: 24rpx;
  font-weight: 500;
  border: none;
  margin-top: 16rpx;
}

.info-section {
  background-color: #fff;
  margin-bottom: 16rpx;
  padding: 24rpx;
  border: 1px solid #f0f0f0;
}

.section-header {
  margin-bottom: 16rpx;
}

.section-title {
  font-size: 26rpx;
  font-weight: 500;
  color: #1a1a1a;
}

.family-card {
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
}

.family-name {
  display: block;
  font-size: 26rpx;
  font-weight: 500;
  margin-bottom: 8rpx;
  color: #2c3e50;
}

.family-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 22rpx;
  color: #7f8c8d;
}

.meta-item {
  margin-right: 20rpx;
}

.invite-code {
  display: flex;
  align-items: center;
}

.copy-btn {
  background-color: #34495e;
  color: white;
  border-radius: 4rpx;
  padding: 4rpx 8rpx;
  font-size: 20rpx;
  margin-left: 8rpx;
  border: none;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12rpx;
}

.stat-item {
  text-align: center;
  padding: 16rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
}

.stat-number {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 20rpx;
  color: #7f8c8d;
}

.logout-section {
  padding: 24rpx;
}

.logout-btn {
  width: 100%;
  background-color: #e74c3c;
  color: white;
  border-radius: 8rpx;
  padding: 16rpx;
  font-size: 24rpx;
  border: none;
}
</style> 